//
//  HMUserAccountViewModel.swift
//  HMWeibo
//
//  Created by wulei on 15/12/9.
//  Copyright © 2015年 wulei. All rights reserved.
//

import Foundation
class HMUserAccountViewModel {
    // 单例
    static let sharedUserAccountViewModel = HMUserAccountViewModel()
    
    
    // 用户模型
    var account: HMUserAccount?
    
    // 归档路径,计算型属性
    var accountPath: String {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    
    // 输出一个有效的access_token
    var accessToken: String? {
        if !isExpired {
            return account?.access_token
        }
        return nil
    }
    
    // 判断用户是否登录成功
    var isLogon: Bool {
        
        return account?.access_token != nil && !isExpired
    }
    
    // 用户头像
    var avatarURL: NSURL {

        return NSURL(string: account?.avatar_large ?? "")!
    }
    
    // 判断帐户是否过期 计算型属性
  private var isExpired: Bool {
//    account?.expiresDate = NSDate(timeIntervalSinceNow: -3600)
    if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
        return false
    }
        
        return true
    }
    
    
    // MARK: - 构造函数
    init() {
       account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? HMUserAccount
        
        if isExpired {
            print("已经过期")
            account = nil
            return
        }
//        print(account)
    }
    
}


// MARK: - 用户帐户相关的方法
extension HMUserAccountViewModel {
    
    // 加载授权码,返回令牌
    func loadAcessToken(code: String, finish:(isSuccess: Bool) -> ()) {
        
        HMNetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            
            // 1> 判断错误
            if  error != nil {
                print("出错了")
                finish(isSuccess: false)
            }
            
            // 2> 输出结果
            //            print(result)
            
            self.account = HMUserAccount(dict:result as! [String: AnyObject])
            
            self.loadUserInfo(self.account!,finish: finish)
            
            
            
        }
    }
    
    
    /// 载入用户信息
    func loadUserInfo(account: HMUserAccount, finish:(isSuccess: Bool) -> ()) {
        HMNetworkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
            if error != nil {
                print("加载用户出错了")
                finish(isSuccess: false)
            }
            
            // 提示 如果使用 if let 或者是 guard let 统统使用"?"
            // as? 作了两个判断
            // 一定有内容
            // 一定是字典
            guard  let dict = result as? [String: AnyObject] else {
                print("格式错误")
                finish(isSuccess: false)
                return
            }
            
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)


            finish(isSuccess: true)
            
            
            
            
        }
    }


}